import { NextFunction, Request, Response } from 'express';

/**
 * 请求拦截，统一处理参数，返回结果（注意注册顺序，要在引入路由之前先注册这个拦截器）
 * @param req
 * @param res
 * @param next
 */
const requestResponseMiddleware = (req: Request, res: Response, next: NextFunction) => {
  /**
   * get, post 参数统一获取 返回键值对
   * @returns
   */
  req.getParams = () => ({ ...req.query, ...req.body, ...req.params });

  /**
   * 正常响应返回
   * @param data
   * @param message
   */
  res.sendSuccess = function (data: unknown, message?: string) {
    res.json({ code: 200, message: message || 'ok', data });
  };

  /**
   * 错误响应返回
   * @param message 错误消息
   * @param code 错误代码
   */
  res.sendError = function (message: string, code: number = 500) {
    res.json({ code, message });
  };
  next();
};

export default requestResponseMiddleware;
